//sqlPool.js
var genericPool = require('generic-pool');
var mysql = require("mysql");

/*
* Create mysql connection pool.
*/
var createMysqlPool = function (app) {
    var mysqlConfig = app.get('mysql');

    const factory = {
        create: function () {
            return new Promise(function (resolve, reject) {

                var client = mysql.createConnection({
                    host: mysqlConfig.host,
                    user: mysqlConfig.user,
                    password: mysqlConfig.password,
                    database: mysqlConfig.database
                });
                client.connect();
                resolve(client);
            });
        },
        destroy: function (client) {
            return new Promise(function (resolve) {
                client.on( function () {
                    resolve();
                });
                client.disconnect();
            })
        }
    };

    var opts = {
        max: 10, // maximum size of the pool
        min: 1 // minimum size of the pool
    };


    return genericPool.createPool(factory, opts);
};
exports.createMysqlPool = createMysqlPool;